<?php
/**
 * Created by Chukintang on 2018/5/20 18:07.
 */

namespace app\common\validate;

use app\common\model\Cate as CateModel;

class CateValidate extends CommonValidate
{

    protected $rule = [
        ['pid', 'require|min:0', '上级分类选择异常|上级分类选择异常',],
        ['cate_name', 'require|checkExistCate', '请输入分类名称|该分类已存在
        '],
        ['cate_sort', 'require|integer|between:0,127', '请输入排序|请输入0-127的排序数字|请输入0-127的排序数字',],
    ];

    protected $scene = [
        'add'  =>  ['pid','cate_name','cate_sort'],
    ];


    /**
     * 检测分类是否存在
     * @desc 检测分类是否存在 
     */
    protected function checkExistCate($value, $rule, $data, $field, $title)
    {
        $cateModel = new CateModel();
        if(isset($data['id'])){
            $result = $cateModel->where(['cate_name' => $value, 'pid' => $data['pid'],'id'=>['<>',$data['id']]])->find();
        }else{
            $result = $cateModel->where(['cate_name' => $value, 'pid' => $data['pid']])->find();
        }
        if ($result) {
            return '该分类已存在';
        }
        return true;
    }

}

